package es.cazadoresmadridejos.util;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import es.cazadoresmadridejos.model.BigGame;
import es.cazadoresmadridejos.model.BigGameAssistance;

public class XmlUtils {

	
	public static ByteArrayInputStream bigGameXml(BigGame bigGame){
		StringBuffer result = new StringBuffer();
		
		result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		result.append("<bigGame>");
		result.append("<date>").append(bigGame.getDecoratedDate()).append("</date>");		
		result.append("<cost>").append(bigGame.getAmount().setScale(0)).append("</cost>");		
		result.append("<arrivalHour>").append(bigGame.getArrivalHour()).append("</arrivalHour>");		
		result.append("<raffleHour>").append(bigGame.getRaffleHour()).append("</raffleHour>");		
		result.append("		<partners>");
		
		List<BigGameAssistance> assistances = bigGame.getAssistances();
		
		Collections.sort(assistances, new BigGameDownloadComparator());
		
		for (BigGameAssistance assistance : assistances) {
			result.append(fillPartner(assistance));
		}
		result.append("		</partners>");		
		result.append("</bigGame>");		
		
		return new ByteArrayInputStream(result.toString().getBytes());
	}
	
	private static String fillPartner(BigGameAssistance assistance){
		StringBuffer sb = new StringBuffer();
		sb.append("<partner>");
		sb.append("		<index>${0}</index>");
		sb.append("		<name>${1} ${2}</name>");
		sb.append("</partner>");
		
		return sb.toString()
				.replace("${0}", assistance.getListIndex().toString())
				.replace("${1}", assistance.getPartner().getName().toUpperCase())
				.replace("${2}", assistance.getPartner().getLastName().toUpperCase());
	}
	
	static class BigGameDownloadComparator implements Comparator<BigGameAssistance>{

		@Override
		public int compare(BigGameAssistance o1, BigGameAssistance o2) {
			if(o2.getListIndex() == null){
				return 1;
			}
			if(o1.getListIndex() == null){
				return -1;
			}
			return o1.getListIndex().compareTo(o2.getListIndex());
		}
		
	}	
}
